package alf.mapping.view.activity;
import alf.mapping.dto.maps.Room;
import alf.mapping.view.Util;
import alf.mapping.view.visuals.EditorEngine;
import alf.mapping.view.visuals.ThemeManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;

public class DiagramEditionActivity extends SimpleAbstractActivity {
	Room diagram;
	String oldTerrain = null;
	String oldMod = null;
	EditorEngine editor;
	Spinner modSelector;
	String[] modNames;

	private static final int REQUEST_IMAGE_SELECT = 1;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.diagram_edit);
		editor = EditorEngine.getInstance();
		diagram = editor.getCurrentRoom();
		Util.setText(this, R.id.diagram_name, diagram.getName());	

		oldMod = diagram.getMod();
		modNames = editor.getTheme().getAvaliableThemes();
		if (modNames != null) {
			modSelector = (Spinner) findViewById(R.id.diagram_mod);
			modSelector.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, modNames));

			for (int i =0;i < modNames.length;i++) {
				if (modNames[i].equals(diagram.getMod())) {
					modSelector.setSelection(i);
				}
			}
		}

		Util.setText(this, R.id.diagram_terrain, diagram.getTerrain());
		oldTerrain = diagram.getTerrain();		
		updateTerrain(oldTerrain);
    }

	private void updateTerrain(String terrain) {
		ImageView imv = (ImageView) this.findViewById(R.id.diagram_terrain_img);
		imv.setImageBitmap(editor.getBitmap(ThemeManager.TERRAIN, terrain));
		Util.setText(this, R.id.diagram_terrain, terrain);
	}

	public void onImageClick(View v) {
		Intent i = new Intent(this, ImageSelectionActivity.class);
		i.setData(ImageSelectionActivity.prepareCall(ThemeManager.TERRAIN, Util.getText(this, R.id.diagram_terrain)));
		startActivityForResult(i, REQUEST_IMAGE_SELECT);
	}


	public void onOk(View v) {
		Intent i = getIntent();
		diagram.setName(Util.getText(this, R.id.diagram_name));
		String newMod = modNames[modSelector.getSelectedItemPosition()];
		if (!newMod.equals(oldMod)) {
			diagram.setMod(newMod);
			editor.onDiagramPropertiesChanged();
		}
		String newTerrain = Util.getText(this, R.id.diagram_terrain);
		if (!newTerrain.equals(oldTerrain)) {
			diagram.setTerrain(newTerrain);
		}
		setResult(RESULT_OK, i);
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case REQUEST_IMAGE_SELECT:
				if (resultCode == Activity.RESULT_OK) {
					String newType = data.getExtras().getString(Intent.EXTRA_RETURN_RESULT);
					updateTerrain(newType);
				}
				break;
		}
	}
}
